//
//  PushManager.swift
//  MovieApiTest
//  推送通知管理
//  使用信鸽推送，需加入以下库CFNetwork.framework , SystemConfiguration.framework , CoreTelephony.framework , libz.dylib , libXG-SDK.a，Security.framework , libsqlite3.dylib
//  Created by linhan on 15/6/18.
//  Copyright (c) 2015年 linhan. All rights reserved.
//

import Foundation
import UIKit

@objc public protocol PushManagerDelegate:NSObjectProtocol
{
    @objc optional func didRegisterForRemoteNotifications(_ deviceToken:String)
    
    @objc optional func didReceiveRemoteNotification(_ userInfo:[AnyHashable : Any])
    
    @objc optional func launchWithRemoteNotification(_ userInfo:[AnyHashable : Any])
}

private let _manager:SWPushManager = SWPushManager()
public class SWPushManager: NSObject
{
    //未读通知
    var unreadNotice:[[AnyHashable: Any]] = []
    
    //通过推送通知启动时带的参数
    public var launchRemoteNotification:[AnyHashable: Any]?
    
    private let KEY_DeviceToken:String = "PushManager_Key_DeviceToken"
    
    private var _observers:[AnyObject] = []
    
    private var _commitedDeviceToken:Bool = false
    
    class func shared()->SWPushManager
    {
        return _manager
    }
    
    override init()
    {
        super.init()
        if let commited = SimpleCookie.shared().getObject(KEY_CommitedDeviceToken) as? Bool
        {
            _commitedDeviceToken = commited
        }
    }
    
    var deviceToken:String
    {
        get
        {
            return SimpleCookie.shared().getObject(KEY_DeviceToken) as? String ?? ""
        }
        set
        {
            SimpleCookie.shared().setObject(newValue, forKey: KEY_DeviceToken)
        }
    }
    
    //是否已经成功提交过DeviceToken
    private let KEY_CommitedDeviceToken:String = "PushManager_Key_CommitedDeviceToken"
    public var commitedDeviceToken:Bool
    {
        get
        {
            return _commitedDeviceToken
        }
        set
        {
            _commitedDeviceToken = newValue
            SimpleCookie.shared().setObject(newValue, forKey: KEY_CommitedDeviceToken)
        }
    }
    
    //添加观察者
    public func addDelegate(_ delegate:AnyObject)
    {
        removeDelegate(delegate)
        _observers.append(delegate)
    }
    
    //移除观察者
    public func removeDelegate(_ delegate:AnyObject)
    {
        for i in (0..<_observers.count).reversed()
        {
            if _observers[i].hashValue == delegate.hashValue
            {
                _observers.remove(at: i)
            }
        }
    }
    
    public func start(_ launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
    {
        //TODO:推送SDK接入
        //JPUSHService.setupWithOption(launchOptions, appKey:SW.Config.JPushAppKey, channel:"AppStore", apsForProduction:true)
        UIApplication.shared.applicationIconBadgeNumber = 0
        
        if let notificationValue = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any]
        {
            launchRemoteNotification = notificationValue
            for i in 0..<self._observers.count
            {
                (self._observers[i] as? PushManagerDelegate)?.launchWithRemoteNotification?(notificationValue)
            }
            
            UIApplication.shared.cancelAllLocalNotifications()
        }
    }
    
    //注册设备
    public func registerDevice(_ deviceToken: Data)
    {
        //TODO:推送SDK接入
        //JPUSHService.registerDeviceToken(deviceToken)
        //注册设备
        if self._observers.count > 0
        {
            //TODO 从deviceToken获取字符型token
            let token = "aaaa"
            for i in 0..<self._observers.count
            {
                (self._observers[i] as? PushManagerDelegate)?.didRegisterForRemoteNotifications?(token)
            }
        }
    }
    
    //接收到推送通知
    public func receiveRemoteNotification(_ userInfo:[AnyHashable : Any])
    {
        //TODO:推送SDK接入
        //JPUSHService.handleRemoteNotification(userInfo)
        
        if _observers.count > 0
        {
            for i in 0..<_observers.count
            {
                (self._observers[i] as? PushManagerDelegate)?.didReceiveRemoteNotification?(userInfo)
            }
        }
        else
        {
            unreadNotice.append(userInfo)
        }
        
        UIApplication.shared.cancelAllLocalNotifications()
    }
    
    //添加一条本地通知
    public func addLocalNotification(_ fireDate:NSDate, alertBody:String, userInfo: [NSObject : AnyObject]? = nil)
    {
        //TODO 3
        /**
        let notification:UILocalNotification = UILocalNotification()
        notification.fireDate = fireDate
        //使用本地时区
        notification.timeZone = NSTimeZone.defaultTimeZone()
        notification.repeatInterval = NSCalendarUnit()
        notification.alertBody = alertBody
        notification.soundName = UILocalNotificationDefaultSoundName
        //notification.alertAction = "打开"
        notification.userInfo = userInfo
        //notification.applicationIconBadgeNumber = 1;
        UIApplication.shared.scheduleLocalNotification(notification)
         **/
    }
    
    public func registerRemoteNotification()
    {
        //println("Registering for push notifications...")
        let application:UIApplication = UIApplication.shared
        application.applicationIconBadgeNumber = 0
        
        
        //本地通知
        if #available(iOS 8.0, *)
        {
            let notificationTypes:UIUserNotificationType = [.badge, .sound, .alert]
            let settings:UIUserNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
            
            application.registerUserNotificationSettings(settings)
        }
        
        //远程通知
        //IOS8
        if #available(iOS 8.0, *)
        {
            application.registerForRemoteNotifications()
        }
        else
        {
            let notificationTypes:UIRemoteNotificationType = [UIRemoteNotificationType.badge, UIRemoteNotificationType.sound, UIRemoteNotificationType.alert]
            application.registerForRemoteNotifications(matching: notificationTypes)
        }
    }
    
    //用户是否允许推送通知
    var enabledRemoteNotification:Bool
    {
        if #available(iOS 8.0, *) {
            return UIApplication.shared.isRegisteredForRemoteNotifications
        } else {
            return UIApplication.shared.enabledRemoteNotificationTypes() != []
        }
    }
    
    //是否允许本地通知
    var enabledLocalNotification:Bool
    {
        var enabled:Bool = true
        if #available(iOS 8.0, *) {
            if let settings = UIApplication.shared.currentUserNotificationSettings , settings.types == []
            {
                enabled = false
            }
        }
        return enabled
    }
    
    private func removeLocalNotification(_ nid:String)
    {
        let app:UIApplication = UIApplication.shared
        if let notifications = UIApplication.shared.scheduledLocalNotifications , notifications.count > 0
        {
            for notification in notifications
            {
                if let userInfo = notification.userInfo,
                   let id = userInfo["nid"] as? String , id == nid
                {
                    app.cancelLocalNotification(notification)
                }
            }
        }
    }
    
    
}
